package io.mya.app.config;

import java.io.IOException;
import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import io.mya.modules.customer.entity.CustomerEntity;

/**
 * 自定义拦截器 验证是否登入和是否多处登入的拦截器
 *
 * @author:shican
 * @date:2018年3月29日
 */
public class MyInterceptor implements HandlerInterceptor {
	  @Autowired
	  private StringRedisTemplate stringRedisTemplate;
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// 如果不是映射到方法直接通过
		if (!(handler instanceof HandlerMethod)) {
			return true;
		}
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		Method method = handlerMethod.getMethod();

		// 判断接口是否需要登录
		LoginRequired methodAnnotation = method.getAnnotation(LoginRequired.class);
		// 有 @LoginRequired 注解，需要认证
		if (methodAnnotation != null) {
			//从session中取出用户信息
	    	Object attribute = request.getSession().getAttribute("user");
	    	if(attribute == null){
	    		request.setAttribute("loginmsg", "您已掉线,请重新登入!");
	    		//response.sendRedirect("/app/child_hmtl/Token_login.html");
	    		redirect(request, response);
	    		return false;
	    	}
	    	CustomerEntity customerEntity = (CustomerEntity) attribute;
			String token = (String) stringRedisTemplate.opsForHash().get("Token",customerEntity.getId().toString());
			if(token.equals(customerEntity.getToken())){
				return true;
	    	}else{
	    		request.getSession().removeAttribute("user");
	    		request.setAttribute("loginmsg", "您已掉线,请重新登入!");
	    		//response.sendRedirect("/app/child_hmtl/Token_login.html");
	    		redirect(request, response);
	    		return false;
	    	}
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		
	}
	  //对于请求是ajax请求重定向问题的处理方法
    public void redirect(HttpServletRequest request, HttpServletResponse response) throws IOException{
        //获取当前请求的路径
        String basePath = request.getScheme() + "://" + request.getServerName() + ":"  + request.getServerPort()+request.getContextPath();
        //如果request.getHeader("X-Requested-With") 返回的是"XMLHttpRequest"说明就是ajax请求，需要特殊处理 否则直接重定向就可以了
        if("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))){
            //告诉ajax我是重定向
            response.setHeader("REDIRECT", "REDIRECT");
            //告诉ajax我重定向的路径
            response.setHeader("CONTENTPATH", basePath+"/app/child_hmtl/Token_login.html");
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        }else{
            response.sendRedirect(basePath + "/app/child_hmtl/Token_login.html");
        }
    }
}
